//
//  GYShopMainViewController.m
//  GoodLuck
//
//  Created by apple on 2018/2/2.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYShopMainViewController.h"
#import "GYBottomTool.h"
#import "GYNetWorkTools.h"
#import "GYMainHeadView.h"
#import "GYMainShopEvaluateCell.h"
#import "GYMainShopCell.h"
#import "GYMainShopSelectCell.h"
#import "GYMainFootView.h"
#import "GYStoreInfoViewController.h"
#import "GYCitySelectViewController.h"
#import "GYShoppingCartView.h"
#import "GYConfirmOrderViewController.h"
#import "GYShopingCartViewController.h"
#import "GYUser.h"
#import "GYShopHomeViewController.h"
#import "GYWebViewViewController.h"
#import <KSPhotoBrowser/KSPhotoBrowser.h>


static NSString *shopIdentifier = @"shopIdentifier";

@interface GYShopMainViewController ()<UITableViewDelegate,UITableViewDataSource,GYBottomToolDeleagte,UIWebViewDelegate>

/** 表格 */
@property (nonatomic, weak) UITableView *tableView;

/** 缓存当前的商品详情数据 */
@property (nonatomic, strong) NSDictionary *cachesGoodsDetailsDic;

/** 透视图 */
@property (nonatomic, strong) GYMainHeadView *headView;

/** 尾视图 */
@property (nonatomic, strong) GYMainFootView *footView;

/** 选择地址 */
@property (nonatomic, strong) NSString *selectAddress;

/** 选择地址的 地区id */
@property (nonatomic, strong) NSString *selectArea_id;

/** 出现购买视图 */
@property (nonatomic, strong) GYShoppingCartView *shoppingCartView;

/** 当前店铺电话 */
@property (nonatomic, strong) NSString *currentStorePhone;

/** 底部工具栏视图 */
@property (nonatomic, strong) GYBottomTool *bottomToolView;
@end

@implementation GYShopMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //NSLog(@"商品id=======%@",self.goods_id);
    //初始化
    [self setupTableView];
    
    //初始化底部工具来栏
    [self setupBottomTool];
    
    //初始化商品数据
    [self setupGoodsDetailsData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //IOS中去掉导航栏20个高度
    if (@available(iOS 11.0,*)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
}

- (void)setupTableView {
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-55-(iPhoneX ? 88 :64)-(iPhoneX ? 44 :0)) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.sectionHeaderHeight = 0;

    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:shopIdentifier];
    
    //透视图有待解决
    GYMainHeadView *headView = [[GYMainHeadView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, heightScale(350, iphone6_H))];
    headView.goods_id = self.goods_id;
    __weak typeof(self) weakSelf = self;
    headView.loginviewCallBack = ^{
        weakSelf.tabBarController.selectedIndex = 2;
        [weakSelf.tabBarController.tabBar setHidden:YES];
    };
    headView.imageClickCallBack = ^(NSArray *images) {
        NSMutableArray *items = [NSMutableArray array];
        for (int i = 0; i < images.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] init];
            KSPhotoItem *item = [KSPhotoItem itemWithSourceView:imageView image:images[i]];
            [items addObject:item];
        }
        KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:items selectedIndex:0];
        [browser showFromViewController:weakSelf];
    };
    tableView.tableHeaderView = headView;
    self.headView = headView;
    
    //表格尾视图
    GYMainFootView *footView = [[[NSBundle mainBundle] loadNibNamed:@"GYMainFootView" owner:nil options:nil] firstObject];
    footView.frame = CGRectMake(0, 0, ScreenWidth, [footView ViewHeight:self.cachesGoodsDetailsDic]);
    
    footView.shopRecommendationClickCallBack = ^(NSString *goods_id) {
        GYShopHomeViewController *shopController = [[GYShopHomeViewController alloc] init];
        shopController.goods_id = goods_id;
        [weakSelf.navigationController pushViewController:shopController animated:YES];
    };
    
    tableView.tableFooterView = footView;
    self.footView = footView;
}

- (void)setupBottomTool {
    GYBottomTool *bottomToolView = [[GYBottomTool alloc] initWithFrame:CGRectMake(0, ScreenHeight-(iPhoneX ? 88 :64)-55-(iPhoneX ? 44 :0), ScreenWidth, 55)];
    bottomToolView.delegate = self;
    [self.view addSubview:bottomToolView];
    self.bottomToolView = bottomToolView;
}

//加载当前商品的详情信心
- (void)setupGoodsDetailsData {
    //NSLog(@"self.goods_id=========%@",self.goods_id);
    [EasyLodingView showLodingText:@"正在加载..."];
   [GYNetWorkTools requestGoodsDetails:self.goods_id success:^(NSDictionary *obj) {
       //NSLog(@"obj=======%@",obj);
       int code = [[obj objectForKey:@"code"] intValue];
       NSDictionary *datas = [obj objectForKey:@"datas"];
       if (code == 200) {
           [EasyLodingView hidenLoding];
           //赋值
           self.headView.images = [datas objectForKey:@"goods_images"];
           self.headView.favorate = [[datas objectForKey:@"is_favorate"] boolValue];
           
           //各位视图赋值
           self.footView.frame = CGRectMake(0, 0, ScreenWidth, [self.footView ViewHeight:datas]);
           self.footView.goodsDetails = datas;
           
           //获取当前店铺号码
           NSDictionary *store_info = [datas objectForKey:@"store_info"];
           self.currentStorePhone = [store_info objectForKey:@"store_phone"];
           
           //缓存
           self.cachesGoodsDetailsDic = datas;
           [self.tableView reloadData];
       }else if (code == 400) {
           [EasyTextView showText:@"亲，您的手机网络不太顺畅喔..."];
           [EasyLodingView hidenLoding];
           NSLog(@"网络架加载数据出错===%@",[datas objectForKey:@"error"]);
       }
   } error:^(NSError *error) {
       [EasyTextView showText:@"亲，您的手机网络不太顺畅喔..."];
       [EasyLodingView hidenLoding];
       NSLog(@"loadGoodsDetailsFailed====%@",error);
   }];
}

#pragma mark -- GYBottomToolDeleagte

- (void)onButtonClick:(NSInteger)tag {
    
    switch (tag) {
        case 1:
        {
            NSLog(@"您点击了客服按钮...%@",self.currentStorePhone);
            [self.shoppingCartView removeFromSuperview];
            GYWebViewViewController *WebCustomerServiceVC = [[GYWebViewViewController alloc] initWithNibName:@"GYWebViewViewController" bundle:nil];
            WebCustomerServiceVC.url = [NSURL URLWithString:@"https://youwei.yunhongkg.com/appapi/index.php?act=message&op=Customer"];
            [self.navigationController pushViewController:WebCustomerServiceVC animated:YES];
        }
            break;
            
        case 2:
        {
            //购物车
            NSLog(@"点击了购物车...");
            if ([GYUser loadUserInfo] != nil) {
                [self.shoppingCartView removeFromSuperview];
                GYShopingCartViewController *shopingCartVC = [[GYShopingCartViewController alloc] initWithNibName:@"GYShopingCartViewController" bundle:nil];
                [self.navigationController pushViewController:shopingCartVC animated:YES];
            }else {
                self.tabBarController.selectedIndex = 2;
                [self.tabBarController.tabBar setHidden:YES];
            }            
        }
            break;
            
        case 3:
        {
#warning 点击这里有问题.....
            //跳转到店铺界面
            NSLog(@"点击店铺...");
            NSDictionary *store_info = [self.cachesGoodsDetailsDic objectForKey:@"store_info"];
            if (store_info != nil) {
                [self.shoppingCartView removeFromSuperview];
                GYStoreInfoViewController *storeInfoVC = [[GYStoreInfoViewController alloc] initWithNibName:@"GYStoreInfoViewController" bundle:nil];
                storeInfoVC.store_id = [store_info objectForKey:@"store_id"];
                storeInfoVC.storePhone = self.currentStorePhone;
                [self.navigationController pushViewController:storeInfoVC animated:YES];
            }
        }
            break;
        
        case 4:
        {
            NSLog(@"点击立即购买....");
            if (self.shoppingCartView != nil) {
                self.shoppingCartView.hidden = NO;
            }else {
                GYShoppingCartView *shoppingView = [[[NSBundle mainBundle] loadNibNamed:@"GYShoppingCartView" owner:nil options:nil] firstObject];
                shoppingView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight- (iPhoneX ? 44 : 0));
                shoppingView.goodsDtailsDic = self.cachesGoodsDetailsDic;
                __weak typeof(self) weakSelf = self;
                shoppingView.goodsBuyprocessCallBack = ^(NSInteger tag,NSInteger goodsCount) {
                    if (tag > 3) {
                        if (tag == 4) {
                            //这里要判断用户有没有登陆  没有则直接
                            if ([GYUser loadUserInfo] != nil) {
                                //立即购买
                                weakSelf.shoppingCartView.hidden = YES;
                                GYConfirmOrderViewController *confirOrderVC = [[GYConfirmOrderViewController alloc] init];
                                confirOrderVC.goods_id = weakSelf.goods_id;
                                confirOrderVC.goodsCount = goodsCount;
                                confirOrderVC.directBuy = YES;
                                [weakSelf.navigationController pushViewController:confirOrderVC animated:YES];
                            }else {
                                [weakSelf.shoppingCartView removeFromSuperview];
                                weakSelf.shoppingCartView = nil;
                                [[NSNotificationCenter defaultCenter] postNotificationName:showLoginView object:nil];
                                weakSelf.tabBarController.selectedIndex = 2;
                                [weakSelf.tabBarController.tabBar setHidden:YES];
                            }
                        }
                    }else {
                        [weakSelf onButtonClick:tag];
                    }
                };
                [[UIApplication sharedApplication].keyWindow addSubview:shoppingView];
                self.shoppingCartView = shoppingView;
            }
        }
            break;
            
        case 5:
        {
            NSLog(@"点击加入购物车....");
            if (self.shoppingCartView != nil) {
                self.shoppingCartView.hidden = NO;
            }else {
                GYShoppingCartView *shoppingView = [[[NSBundle mainBundle] loadNibNamed:@"GYShoppingCartView" owner:nil options:nil] firstObject];
                shoppingView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-(iPhoneX ? 44 : 0));
                shoppingView.goodsDtailsDic = self.cachesGoodsDetailsDic;
                __weak typeof(self) weakSelf = self;
                shoppingView.goodsBuyprocessCallBack = ^(NSInteger tag,NSInteger goodsCount) {
                    if (tag > 3) {
                        if (tag == 4) {
                            //这里要判断用户有没有登陆  没有则直接
                            if ([GYUser loadUserInfo] != nil) {
                                //立即购买
                                weakSelf.shoppingCartView.hidden = YES;
                                GYConfirmOrderViewController *confirOrderVC = [[GYConfirmOrderViewController alloc] init];
                                confirOrderVC.goods_id = weakSelf.goods_id;
                                confirOrderVC.goodsCount = goodsCount;
                                confirOrderVC.directBuy = YES;
                                [weakSelf.navigationController pushViewController:confirOrderVC animated:YES];
                            }else {
                                [weakSelf.shoppingCartView removeFromSuperview];
                                weakSelf.shoppingCartView = nil;
                                [[NSNotificationCenter defaultCenter] postNotificationName:showLoginView object:nil];
                                weakSelf.tabBarController.selectedIndex = 2;
                                [weakSelf.tabBarController.tabBar setHidden:YES];
                            }
                        }
                    }else {
                        [weakSelf onButtonClick:tag];
                    }
                };
                [[UIApplication sharedApplication].keyWindow addSubview:shoppingView];
                self.shoppingCartView = shoppingView;
            }
        }
            break;
    }
}


#pragma mark -- UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        GYMainShopSelectCell *cell = [GYMainShopSelectCell mainShopSelectCellWithTableView:tableView];
        cell.goodsDetails = self.cachesGoodsDetailsDic;
        __weak typeof(self) weakSelf = self;
        cell.selectGoodsDistrbutionAddressCallBack = ^{
            //选择地址并且 看到运费
            GYCitySelectViewController *citySelectVC = [[GYCitySelectViewController alloc] initWithNibName:@"GYCitySelectViewController" bundle:nil];
            citySelectVC.block = ^(NSString *addressName, NSString *province_id, NSString *city_id, NSString *area_id) {
                
                weakSelf.selectAddress = addressName;
                weakSelf.selectArea_id = area_id;
                [weakSelf.tableView reloadData];
            };
            [weakSelf.navigationController pushViewController:citySelectVC animated:YES];
        };
        
        cell.defaultBtuClickCallBack = ^{
            if (weakSelf.shoppingCartView != nil) {
                weakSelf.shoppingCartView.hidden = NO;
            }else {
                GYShoppingCartView *shoppingView = [[[NSBundle mainBundle] loadNibNamed:@"GYShoppingCartView" owner:nil options:nil] firstObject];
                shoppingView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
                shoppingView.goodsDtailsDic = weakSelf.cachesGoodsDetailsDic;
                shoppingView.goodsBuyprocessCallBack = ^(NSInteger tag,NSInteger goodsCount) {
                    if (tag > 3) {
                        if (tag == 4) {
                            //这里要判断用户有没有登陆  没有则直接
                            if ([GYUser loadUserInfo] != nil) {
                                //立即购买
                                weakSelf.shoppingCartView.hidden = YES;
                                GYConfirmOrderViewController *confirOrderVC = [[GYConfirmOrderViewController alloc] init];
                                confirOrderVC.goods_id = weakSelf.goods_id;
                                confirOrderVC.goodsCount = goodsCount;
                                confirOrderVC.directBuy = YES;
                                [weakSelf.navigationController pushViewController:confirOrderVC animated:YES];
                            }else {
                                [weakSelf.shoppingCartView removeFromSuperview];
                                weakSelf.tabBarController.selectedIndex = 2;
                                [weakSelf.tabBarController.tabBar setHidden:YES];
                            }
                        }
                    }else {
                        [weakSelf onButtonClick:tag];
                    }
                };
                [[UIApplication sharedApplication].keyWindow addSubview:shoppingView];
                weakSelf.shoppingCartView = shoppingView;
            }

        };
        
        cell.selectAddress = self.selectAddress;
        cell.selectAread_id = self.selectArea_id;
        
        return cell;
    }else if (indexPath.section == 1) {
        GYMainShopEvaluateCell *cell = [GYMainShopEvaluateCell mainShopEvaluateCellWithTableView:tableView];
        //赋值
        NSDictionary *goods_evaluate_info = [self.cachesGoodsDetailsDic objectForKey:@"goods_evaluate_info"];
        cell.goodsPercentLable.text = [NSString stringWithFormat:@"好评率 %d%@",[[goods_evaluate_info objectForKey:@"good_percent"] intValue],@"%"];
        cell.numEvaluateLable.text = [NSString stringWithFormat:@"(%d人评价)",[[goods_evaluate_info objectForKey:@"all"] intValue]];
        
        return cell;
    }else if (indexPath.section == 2){
        GYMainShopCell *cell = [GYMainShopCell mainShopCellWithTableView:tableView];
        cell.goodsDetails = self.cachesGoodsDetailsDic;
        
        return cell;
    }else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:shopIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.text = @"店铺推荐";
        cell.textLabel.textColor = RGBColor(150, 150, 150);
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 ) {
        //跳转界面
        self.jumpEvaluateViewCallBack(2);
    }else if (indexPath.section == 2){
        //跳转到店铺界面
        NSDictionary *store_info = [self.cachesGoodsDetailsDic objectForKey:@"store_info"];
        if (store_info != nil) {
            GYStoreInfoViewController *storeInfoVC = [[GYStoreInfoViewController alloc] initWithNibName:@"GYStoreInfoViewController" bundle:nil];
            storeInfoVC.storePhone = self.currentStorePhone;
            storeInfoVC.store_id = [store_info objectForKey:@"store_id"];
            [self.navigationController pushViewController:storeInfoVC animated:YES];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
        {
            GYMainShopSelectCell *cell = [GYMainShopSelectCell mainShopSelectCellWithTableView:tableView];
        
            return [cell cellHeight:self.cachesGoodsDetailsDic];
        }
            break;
        
        case 1:
        {
            return 44;
        }
            break;
            
        case 2:
        {
            GYMainShopCell *cell = [GYMainShopCell mainShopCellWithTableView:tableView];
            
            return [cell cellHeight:self.cachesGoodsDetailsDic];
        }
            break;
            
        case 3:
        {
            return 44;
        }
            break;
            
        default:
            break;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 3) {
        return CGFLOAT_MIN;
    }else {
        return 10;
    }
}

- (void)dealloc {
    [self.shoppingCartView removeFromSuperview];
    self.shoppingCartView = nil;
    NSLog(@"GYShopMainViewController===dealloc");
}
@end
